// 表格基础CRUD 逻辑Hook
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

const useTable = ({ apiFn, delApiFn, resCallback }) => {
  // * 表格相关数据
  const tableData = ref([])
  const loading = ref(false)
  const pager = reactive({ total: 0, page: 1 })
  const queryForm = reactive({})

  // * 获取表格数据
  const getData = async () => {
    // 1. 处理参数
    const query = { page: pager.page, ...queryForm }
    // 2. 发起请求
    loading.value = true
    const res = await apiFn(query)
    // 3. 处理响应值 [有自定义逻辑就执行自定义逻辑]
    if (resCallback) return resCallback(res)
    const { data } = res
    tableData.value = data.data
    pager.total = data.count
    loading.value = false
  }

  // * 页码变化
  const pageChange = (index) => {
    pager.page = index
    getData()
  }

  // * 删除表格项
  const handleDel = async (_id) => {
    try {
      await ElMessageBox.confirm('你确定要删除吗?', '提示', { confirmButtonText: '删除' })
      await delApiFn({ _id })
      ElMessage.success('操作成功')
      getData()
    } catch (error) {
      console.log('点击了取消')
    }
  }

  // * 页面加载
  onMounted(() => {
    getData()
  })

  return { tableData, loading, pager, queryForm, getData, handleDel, pageChange }
}

export default useTable
